﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Enterprise.Model.Role;
using Enterprise.Service.Role;
using Enterprise.Model.Module;
using Enterprise.Service.Module;
using Enterprise.Infrastructure;
using Enterprise.Control;
using Enterprise.Model.User;
using Enterprise.Service.User;
using Enterprise.Model.Department;
using Enterprise.Service.Department;
namespace Enterprise.UI.Web.Manage.Role
{
    public partial class Detail : System.Web.UI.Page
    {
        int Id = (int)Utility.sink("Id", Utility.MethodType.Get, 0, 0, Utility.DataType.Int);
        string Cmd = (string)Utility.sink("Cmd", Utility.MethodType.Get, 0, 0, Utility.DataType.Str);
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                OnStart();
            }
        }

        private void OnStart()
        {
            RoleService ser = new RoleService();
            var q = ser.RoleDisp(Id);
            if (q != null)
            {
                Role_Name.Text = q.RNAME;
                Role_Remark.Text = q.RREMARK;

                OnDisp();
                FormatUser();
                OnBindUser();
            }            
        }

        private void OnDisp()
        {
            ModuleService ser = new ModuleService();
            var list = ser.ModuleList().Where(p => p.MPARENTID == 0 && p.MDELETE == "0").OrderBy(p => p.MORDERBY).ToList();
            Module_Main.DataSource = list;
            Module_Main.DataBind();
            if (Cmd == "")
            {
                CreateBT.AddButton("Detail.aspx?Id=" + Id + "&Cmd=Edit", Utility.PopedomType.Edit, HeadMenuWebControls1);
                CreateBT.AddButton("back.gif", "返回", "Index.aspx", Utility.PopedomType.List, HeadMenuWebControls1);
            }
            else if (Cmd == "Edit")
            {
                CreateBT.AddButton("back.gif", "返回", "Detail.aspx?Id=" + Id, Utility.PopedomType.List, HeadMenuWebControls1);
                ButtonTr_End.Visible = true;
            }
        }

         protected void Module_Main_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            var sysModule = (ModuleEntity)e.Item.DataItem;
            if (sysModule != null)
            {
                ModuleService ser = new ModuleService();
                List<ModuleEntity> lst = ser.ModuleList().Where(p => p.MPARENTID == sysModule.MODULEID && p.MDELETE == "0").OrderBy(p => p.MORDERBY).ToList();
                if (lst.Count > 0)
                {
                    Repeater Module_Sub = (Repeater)e.Item.FindControl("Module_Sub");
                    Module_Sub.DataSource = lst;
                    Module_Sub.DataBind();
                }
            }
        }

        protected void Module_Sub_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            var sysModule = (ModuleEntity)e.Item.DataItem;
            if (sysModule != null)
            {
                ModuleService ser = new ModuleService();
                List<ModuleEntity> list = ser.ModuleList().Where(p => p.MPARENTID == sysModule.MODULEID && p.MDELETE == "0").OrderBy(p => p.MORDERBY).ToList();
                if (list.Count > 0)
                {
                    Repeater Module_Sub1 = (Repeater)e.Item.FindControl("Module_Sub1");
                    Module_Sub1.DataSource = list;
                    Module_Sub1.DataBind();
                }
                RolePermissionService rpService = new RolePermissionService();
                var sysRolePermission = rpService.RolePermissionList().Where(p => p.ROLEID == Id && p.MCODE == sysModule.MCODE).FirstOrDefault();
                if (sysRolePermission == null)
                {
                    sysRolePermission = new RolePermissionEntity();
                }
                string rightString = string.Format("<img src='{0}'>", ResolveClientUrl("~/Manage/Common/img/right.gif"));
                string wrongString = string.Format("<img src='{0}'>", ResolveClientUrl("~/Manage/Common/img/wrong.gif"));
                string dispString = "";
                string SelectTxt = "";
                int TempStep = 1;
                for (int i = 0; i < 8; i++)
                {
                    TempStep = TempStep + TempStep;
                    Literal li = (Literal)e.Item.FindControl(string.Format("Lab{0}_Txt", TempStep));
                    if (li != null)
                    {
                        if ((sysRolePermission.PERMISSIONVALUE & TempStep) == TempStep)
                        {
                            dispString = rightString;
                            SelectTxt = "checked";
                        }
                        else
                        {
                            dispString = wrongString;
                            SelectTxt = "";
                        }
                        if (Cmd == "Edit")
                        {
                            dispString = string.Format("<input type=checkbox id='PageCode{0}' name='PageCode{0}' value={1}  {2}>", sysModule.MCODE, TempStep, SelectTxt);
                        }
                        li.Text = dispString;
                    }
                }
            }      
        }

        protected void Module_Sub1_OnItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            var sysModule = (ModuleEntity)e.Item.DataItem;
            if (sysModule != null)
            {
                RolePermissionService rpService = new RolePermissionService();
                var sysRolePermission = rpService.RolePermissionList().Where(p => p.ROLEID == Id && p.MCODE == sysModule.MCODE).FirstOrDefault();
                if (sysRolePermission == null)
                {
                    sysRolePermission = new RolePermissionEntity();
                }
                string rightString = string.Format("<img src='{0}'>", ResolveClientUrl("~/Manage/Common/img/right.gif"));
                string wrongString = string.Format("<img src='{0}'>", ResolveClientUrl("~/Manage/Common/img/wrong.gif"));
                string dispString = "";
                string SelectTxt = "";
                int TempStep = 1;
                for (int i = 0; i < 8; i++)
                {
                    TempStep = TempStep + TempStep;
                    Literal li = (Literal)e.Item.FindControl(string.Format("Lab2{0}_Txt", TempStep));
                    if (li != null)
                    {
                        if ((sysRolePermission.PERMISSIONVALUE & TempStep) == TempStep)
                        {
                            dispString = rightString;
                            SelectTxt = "checked";
                        }
                        else
                        {
                            dispString = wrongString;
                            SelectTxt = "";
                        }
                        if (Cmd == "Edit")
                        {
                            dispString = string.Format("<input type=checkbox id='PageCode{0}' name='PageCode{0}' value={1}  {2}>", sysModule.MCODE, TempStep, SelectTxt);

                        }
                        li.Text = dispString;
                    }
                }
            }  
        }

        private void FormatUser()
        {
            string s = "";
            List<UserRoleEntity> list = UserRoleService.UserRoleList().Where(p => p.ROLEID == Id).ToList();
            if (list.Count > 0)
            {
                foreach (UserRoleEntity rm in list)
                {
                    s += UserService.GetUserName(rm.USERID) + ",";
                }
            }
            labelUser.Text = s.TrimEnd(',');
        }

        protected void Button1_Click(object sender, EventArgs e)
        {

            //更新前把RoleId相关内容项
            RolePermissionEntity old = new RolePermissionEntity();
            old.ROLEID = Id;
            old.DB_Option_Action = "Delete";
            RolePermissionService service = new RolePermissionService();
            service.RolePermissionExecute(old);

            //取得表单的值进行更新
            RolePermissionEntity sysRolePM = new RolePermissionEntity();
            sysRolePM.DB_Option_Action = "Insert";
            sysRolePM.ROLEID = Id;

            string TempPageCodeString = "";
            string[] ArrayInt;
            int PageCodeValue = 0;

            foreach (string var in Request.Form)
            {
                if (var.Length > 8)
                {
                    TempPageCodeString = var.Substring(0, 8);
                    if (TempPageCodeString == "PageCode")
                    {
                        PageCodeValue = 0;
                        TempPageCodeString = var.Substring(8, var.Length - 8);
                        ArrayInt = Request.Form[var].Split(',');
                        for (int i = 0; i < ArrayInt.Length; i++)
                        {
                            PageCodeValue = PageCodeValue + Convert.ToInt32(ArrayInt[i]);
                        }
                        sysRolePM.MCODE = TempPageCodeString;
                        sysRolePM.PERMISSIONVALUE = PageCodeValue;
                        service.RolePermissionExecute(sysRolePM);
                    }
                }
            }
            Response.Redirect("Detail.aspx?Id=" + Id);
            Response.End();
        }

        private void OnBindUser()
        {
            DepartmentService dService = new DepartmentService();
            var list = dService.DepartmentList().OrderBy(p => p.DORDERBY);
            tb_Dept.DataSource = list;
            tb_Dept.DataTextField = "DNAME";
            tb_Dept.DataValueField = "DEPTID";
            tb_Dept.DataBind();
            tb_Dept.Items.Insert(0, new ListItem("请选择部门", "0"));
        }

        protected void tb_Dept_SelectedIndexChanged(object sender, EventArgs e)
        {
            tb_User.Items.Clear();
            int deptId = (int)Utility.sink(tb_Dept.UniqueID, Utility.MethodType.Post, 0, 0, Utility.DataType.Int);
            if (deptId != 0)
            {
                UserService uService = new UserService();
                var list = uService.UserList().Where(p => p.DEPTID == deptId).OrderBy(p => p.UORDERBY);
                tb_User.DataSource = list;
                tb_User.DataTextField = "UNAME";
                tb_User.DataValueField = "USERID";
                tb_User.DataBind();
                tb_User.Items.Insert(0, new ListItem("请选择人员", "0"));
            }
        }

        protected void Button2_OnClick(object sender, EventArgs e)
        {
            int uId = (int)Utility.sink(tb_User.UniqueID, Utility.MethodType.Post, 0, 0, Utility.DataType.Int);
            if (uId != 0)
            {
                var q = UserRoleService.UserRoleList().Where(p => p.USERID == uId && p.ROLEID == Id).FirstOrDefault();
                if (q == null)
                {
                    UserRoleEntity entity = new UserRoleEntity();
                    entity.USERID = uId;
                    entity.ROLEID = Id;
                    entity.DB_Option_Action = "Insert";
                    UserRoleService service = new UserRoleService();
                    service.UserRoleExecute(entity);

                    //刷新数据
                    FormatUser();
                }
            }
            else
            {
                UserService uService=new UserService();
                List<UserEntity> list = uService.UserList();
                foreach (var var in list)
                {
                    var q = UserRoleService.UserRoleList().Where(p => p.USERID == var.USERID && p.ROLEID == Id).FirstOrDefault();
                    if (q == null)
                    {
                        UserRoleEntity entity = new UserRoleEntity();
                        entity.USERID = var.USERID;
                        entity.ROLEID = Id;
                        entity.DB_Option_Action = "Insert";
                        UserRoleService service = new UserRoleService();
                        service.UserRoleExecute(entity);
                    }
                }
                //刷新数据
                FormatUser();
            }
        }


    }
}